//===============================
//  功能 ：备注 
//  作者 ：上中野辅亚瑟王 
//  创建时间 ：2023-05-31  16-02-39 
//  Unity版本  ：2019.4.35f1 
//  变更时间 :  2023-05-31  16-02-39 
//===============================





using System;
using System.Collections.Generic;

namespace ZS.U3D.BASE.Runtime.Event
{
    public class EventGroup
    {
        private readonly Dictionary<Type, List<Action<IEvent>>> _cachedListener = new Dictionary<Type, List<Action<IEvent>>>();

        /// <summary>
        /// 添加监听
        /// </summary>
        /// <typeparam name="TEvent"></typeparam>
        /// <param name="listener"></param>
        public void AddListener<TEvent>(Action<IEvent> listener) where TEvent : IEvent {
            Type eventType = typeof(TEvent);
            if (_cachedListener.ContainsKey(eventType) == false)
            {
                _cachedListener.Add(eventType, new List<Action<IEvent>>());
            }

            if (_cachedListener[eventType].Contains(listener) == false)
            {
                _cachedListener[eventType].Add(listener);
            }
            else
            {
                MyDebug.LogWarning($"Event Listener is Exist : {eventType} : {listener}");
            }
        }

        /// <summary>
        /// 移除所有缓存的监听
        /// </summary>
        public void RemoveAllListener() {
            foreach (var pair in _cachedListener)
            {
                Type eventType = pair.Key;
                for (int i = 0; i < pair.Value.Count; i++)
                {
                    EventManager.RemoveListener(eventType,pair.Value[i]);
                }
                pair.Value.Clear();
            }
            _cachedListener.Clear();
        }

    }
}
